package j_log

import (
	"config-client-v1/utils/tools"
	"fmt"
	"log"
)

type LogLevel int

var ConsoleOutput = true
var ConsoleSave = false
var ConsoleOutputLevel = 0
var ConsoleSaveLevel = 2

const (
	LOG_DEBUG   LogLevel = 0
	LOG_INFO    LogLevel = 1
	LOG_WARNING LogLevel = 2
	LOG_ERROR   LogLevel = 3
	LOG_FATAL   LogLevel = 4
)

func LogDebug(data []interface{}) {
	LogHandle(LOG_DEBUG, data)
}

func LogInfo(data []interface{}) {
	LogHandle(LOG_INFO, data)
}
func LogWarning(data []interface{}) {
	LogHandle(LOG_WARNING, data)
}

func LogError(data []interface{}) {
	LogHandle(LOG_ERROR, data)
}

func LogHandle(level LogLevel, a []interface{}) {
	levelName := ""
	switch level {
	case LOG_DEBUG:
		levelName = "debug"
	case LOG_INFO:
		levelName = "info"
	case LOG_WARNING:
		levelName = "warning"
	case LOG_ERROR:
		levelName = "error"
	case LOG_FATAL:
		levelName = "fatal"
	default:
		log.Fatalln("invalid console level")
	}
	s := ""
	s += fmt.Sprintf("[%s] <%s> ", tools.GetNow(), levelName)
	for _, v := range a {
		s += fmt.Sprintf("%v ", v)
	}
	s += fmt.Sprintf("\n")
	if ConsoleOutput && level >= LogLevel(ConsoleOutputLevel) {
		fmt.Printf(s)
		//AppendLog(&StdLogStu{
		//	Data: s,
		//})
	}
	if ConsoleSave && level >= LogLevel(ConsoleSaveLevel) {
		err := tools.WriteStringToLog(s, levelName+".log", "")
		if err != nil {
			fmt.Println("ERROR WriteStringToLog", err.Error())
		}
	}
}

type StdLogStu struct {
	Data string `json:"data"`
}

var StdLog []*StdLogStu

func AppendLog(data *StdLogStu) {
	if len(StdLog) >= 10000 {
		StdLog = StdLog[1:]
	}
	StdLog = append(StdLog, data)
}

func GetLogList(limit int) []*StdLogStu {
	if limit < len(StdLog) {
		return StdLog[len(StdLog)-limit:]
	}
	return StdLog
}
